<template>
  <div class="padding-middle">
    <el-card>
      <el-form ref="ruleForm" :model="postForm" :rules="rules" class="demo-ruleForm">
        <el-form-item prop="title">
          <MDinput v-model="postForm.title" :maxlength="100" required>
            标题
          </MDinput>
        </el-form-item>
        <el-form-item label-width="60px" label="封面:" prop="titlePicUrl">
          <el-upload
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            :action="version + '/uploadFile'"
            class="avatar-uploader"
            name="file">
            <img v-if="postForm.titlePicUrl" :src="version + '/uploadFile/path/' + postForm.titlePicUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label-width="60px" label="内容:" prop="describes">
          <div ref="editor" style="text-align:left; z-index: 0; margin-bottom: 20px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit('ruleForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import MDinput from '@/components/MDinput'
import axios from 'axios'
import E from 'wangeditor'
import { assignment } from '@/utils/assignment'
import { VERSION } from '@/constants/uri'
import { HOME_ITEM } from '@/constants/storage'
let editor = null
export default {
  components: { MDinput },
  props: {
    type: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      postForm: {
        title: '',
        type: this.type,
        titlePicUrl: '',
        describes: ''
      },
      version: VERSION,
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        titlePicUrl: [
          { required: true, message: '请上传封面', trigger: 'blur' }
        ],
        describes: [
          { required: true, message: '是输入内容', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.initEditor()
    if (this.$route.params.id) {
      this.query(this.$route.params.id)
    }
  },
  methods: {
    query(id) {
      const item = JSON.parse(sessionStorage.getItem(HOME_ITEM))
      assignment(this.postForm, item)
      editor.txt.html(item.describes)
    },
    initEditor() {
      editor = new E(this.$refs.editor)
      editor.customConfig.uploadImgShowBase64 = true
      editor.customConfig.showLinkImg = false
      editor.customConfig.zIndex = 0
      editor.customConfig.uploadImgServer = this.version + '/uploadFile'
      editor.customConfig.uploadFileName = 'file'
      editor.customConfig.onchange = (html) => {
        this.editorContent = html
      }
      editor.customConfig.uploadImgHooks = {
        customInsert: function(insertImg, result, editor) {
          // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
          // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
          // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
          insertImg(VERSION + '/uploadFile/path/' + result.fileUploadPath)
          // result 必须是一个 JSON 格式字符串！！！否则报错
        }
      }
      editor.create()
    },
    onSubmit(formName) {
      this.postForm.describes = editor.txt.html()
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return
        }
        if (this.$route.params.id) {
          this.postForm.id = this.$route.params.id
        }
        axios.post('/saveMessageRelease', this.postForm).then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.$router.back()
          }
        })
      })
    },
    handleAvatarSuccess(res, file) {
      if (res.success) {
        this.postForm.titlePicUrl = res.fileUploadPath
      }
    },
    beforeAvatarUpload(file) {
      const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
      if (!isImage) {
        this.$message.error('请上传图片!')
      }
      return isImage
    }
  }
}
</script>

<style lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 400px;
    height: 178px;
    display: block;
  }
</style>
